#pragma once

#include <iostream>
#include <string>
#include <stdlib.h>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Err.hpp"

static const int defaultepfd = -1;
static const int gsize = 128;

class Epoller
{
public:
    Epoller():epfd_(defaultepfd)
    {}

    void Create()
    {
        epfd_ = epoll_create(gsize);//这个参数只要大于0就行
        if(epfd_ < 0)
        {
            logMessage(Fatal, "epoll_create error, code: %d, errstring: %s", errno, strerror(errno));
            exit(EPOLL_CREAT_ERR);
        }
    }

    bool AddEvent(int fd, uint32_t event)
    {
        //填写epoll_event结构体字段
        struct epoll_event et;
        et.events = event;
        et.data.fd = fd;

        int n = epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &et);
        if(n < 0)
        {
            logMessage(Fatal, "epoll_ctl error, code: %d, errstring: %s", errno, strerror(errno));
            return false;
        }
        return true;
    }
    int Wait(struct epoll_event *revs, int num, int timeout)
    {
        // 
        return epoll_wait(epfd_, revs, num, timeout);
    }
    
    bool DelEvent(int fd)
    {
        // epoll在操作fd的时候，有一个要求，fd必须合法！
        return epoll_ctl(epfd_, fd, EPOLL_CTL_ADD, nullptr) == 0;
    }
    int Fd()
    {
        return epfd_;
    }

    ~Epoller()
    {}
private:
    int epfd_;//epoll模型的fd
};